<template>
    <div>
        <el-dialog :title="title" :visible.sync="dialogVisible" width="85%" @close="handleClose">
            <el-form :model="form" :rules="rules" ref="form" label-width="150px" class="demo-ruleForm" v-loading="loading">
                <el-tabs v-model="activeName" type="card">
                    <el-tab-pane label="基本信息" name="1">
                        <el-row :gutter="20">
                            <el-col :span="12">
                                <el-form-item label="标题" prop="name">
                                    <el-input type="textarea" v-model="form.name" maxlength="200"
                                        show-word-limit></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="关键字" prop="keyword">
                                    <el-input type="textarea" v-model="form.keyword" maxlength="200" show-word-limit>
                                    </el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="描述" prop="description">
                                    <el-input type="textarea" v-model="form.description" maxlength="500"
                                        show-word-limit></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="备注" prop="remark">
                                    <el-input type="textarea" v-model="form.remark" maxlength="500"
                                        show-word-limit></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12" class="newDesc">
                                <el-checkbox v-model="checked" @change="changeLink"></el-checkbox>
                                <el-form-item label="来源" prop="ntSource">
                                    <el-input :disabled="checked === false" type="textarea" v-model="form.ntSource"
                                        maxlength="500" show-word-limit></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12" v-if="checked">
                                <el-form-item label="来源链接" prop="ntLink">
                                    <el-input type="textarea" v-model="form.ntLink" maxlength="500"
                                        show-word-limit></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="附件">
                                    <el-upload :action="imageUploadUrl" name="file" :on-success="handleAvatarSuccess6"
                                        :on-error="handleError6" :on-remove="handleRemove6" :file-list="fileAll">
                                        <el-button size="small" type="primary" plain>点击上传</el-button>
                                        <div slot="tip" class="el-upload__tip">
                                            上传文件大小不超过10M
                                        </div>
                                    </el-upload>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item class="newIpt" ref="headimgUpload1" label="封面图片" prop="ntThumb">
                                    <p class="uploadTip">上传图片不超过10M，且只能上传jpg、png类型</p>
                                    <el-upload class="avatar-uploader" :action="imageUploadUrl" :show-file-list="false"
                                        :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload"
                                        :on-error="handleError">
                                        <img v-if="imgUrl" :src="imgUrl" class="avatar">
                                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                                    </el-upload>
                                </el-form-item>
                            </el-col>

                        </el-row>
                    </el-tab-pane>
                    <el-tab-pane label="资讯内容" name="2">
                        <el-form-item label="资讯内容" prop="content">
                            <div style="border: 1px solid #ccc;width:98%;line-height:21px;">
                                <Toolbar style="border-bottom: 1px solid #ccc" :editor="editor"
                                    :defaultConfig="toolbarConfig" :mode="mode" />
                                <Editor v-if="dialogVisible" style="height: 400px; overflow-y: hidden;"
                                    v-model="form.content" :defaultConfig="editorConfig" :mode="mode"
                                    @onCreated="onCreated" />
                            </div>
                        </el-form-item>
                    </el-tab-pane>
                </el-tabs>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitForm">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>
import { getNewOptions, getNewDetail } from "@/request/api/new"
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { getUploadImg } from "@/request/api/link"
export default {
    components: { Editor, Toolbar },
    data() {
        return {
            isWrite: false,
            checked: false,
            dialogVisible: false,
            type: "",
            title: "",
            activeName: '1',
            form: {
                name: "",//政策标题
                keyword: "",//关键字
                description: "",// 描述
                ntThumb: "",//封面图片
                ntCtgId: "", //政策所属栏目
                content: "",// 发布内容
                remark: "", //备注
                status: "0",//新闻状态：0草稿 1已发布
                ntSource: "",//来源
                ntLink: "",//外部链接
                fileDtos: [
                    // {
                    //     name:'',//附件名称
                    //     filePath:''//附件路径
                    // }
                ]//附件
            },
            imgUrl: '',
            rules: {
                name: [
                    { required: true, message: '请输入标题', trigger: 'blur' },
                ],
                keyword: [
                    { required: true, message: '请输入关键字', trigger: 'blur' },
                ],
                description: [
                    { required: true, message: '请输入描述', trigger: 'blur' },
                ],
                content: [
                    { required: true, message: '请输入资讯内容', trigger: 'blur' },
                ],
                status: [
                    { required: true, message: '请选择', trigger: 'change' },
                ],
            },
            selectCate: {
                checkStrictly: true,
                label: "name",
                children: "childs",
                value: "name",
                getCheckedNodes: true,
                expandTrigger: "hover",
            },
            dataTree: [],
            fileAll: [],
            imageUploadUrl: '/dev-api/file/upload/uploadNotQR',
            editor: null,
            toolbarConfig: {//工具栏配置
                excludeKeys: [
                    'insertTable',//插入表格
                ]
            },
            editorConfig: {
                placeholder: '请输入内容...',
                // 所有的菜单配置，都要在 MENU_CONF 属性下
                MENU_CONF: {
                    //配置上传图片
                    uploadImage: {
                        customUpload: this.uploadImg,
                    },
                    //配置上传视频
                    uploadVideo: {
                        customUpload: this.uploadVideo
                    }
                },
            },
            mode: 'default', // or 'simple'
            loading: true,
        };
    },
    methods: {
        open(type, cateInfo, info) {
            //使用富文本的清空方法clear，来清空富文本数据。
            // proxy.$refs['itemRef'].clear();
            this.loading = false
            this.activeName = '1',
                this.type = type;
            this.dialogVisible = true;
            if (this.type === "add") {
                this.title = "新增资讯-" + cateInfo.cateName;
                let params = {
                    name: "",//政策标题
                    keyword: "",//关键字
                    description: "",// 描述
                    ntThumb: "",//封面图片
                    ntCtgId: "", //政策所属栏目
                    content: "",// 发布内容
                    remark: "", //备注
                    status: "0",//新闻状态：0未发送 1已发送
                    ntSource: "",//来源
                    ntLink: "",//外部链接
                    fileDtos: [
                        // {
                        //     name:'',//附件名称
                        //     filePath:''//附件路径
                        // }
                    ]//附件
                }
                this.form = params
                this.form.ntCtgId = cateInfo.cateId
                this.fileAll = []
                this.imgUrl = ''
            } else if (this.type === "edit") {
                this.form.content = info.content
                this.title = "编辑资讯-" + cateInfo.cateName;
                this.fileAll = []
                this.form.fileDtos = []
                this.form.name = info.name
                this.form.keyword = info.keyword
                this.form.description = info.description
                this.form.ntThumb = info.ntThumb
                this.form.ntCtgId = info.ntCtgId

                this.form.remark = info.remark
                this.form.ntLink = info.ntLink
                this.form.status = info.status
                this.form.ntSource = info.ntSource
                // this.form.fileDtos = info.fileDtos
                this.form.id = info.id
                this.imgUrl = info.ntThumb

                if (this.form.ntLink) {
                    this.checked = true
                }
                this.getDetail(info.id)
            }
        },
        // 选择来源
        changeLink(val) {
            // if(){}
        },
        handleClose() {
            this.$emit('getNewList')
            this.$refs.form.resetFields();
            const editor = this.editor
            if (editor == null) return
            editor.destroy() // 组件销毁时，及时销毁编辑器

        },
        // 父级
        selectValue() {
            this.$refs.cascader.dropDownVisible = false;
        },
        // 创建
        submitForm() {
            this.$refs.form.validate((valid) => {
                if (valid) {
                    const loading = this.$loading({
                        lock: true,
                        text: 'Loading',
                        spinner: 'el-icon-loading',
                        background: 'rgba(0, 0, 0, 0.7)'
                    });
                    if (this.type === 'add') {
                        if (this.checked === false) {
                            this.form.ntSource = ''
                            this.form.ntLink = ''
                        }
                        getNewOptions(this.form).then((res) => {

                            loading.close();
                            if (res.data.code === 200) {
                                this.$message({
                                    message: res.data.message,
                                    type: "success",
                                });
                                this.$emit('getNewList')
                                this.dialogVisible = false

                            } else {
                                this.$message.error(res.data.message);
                            }
                        });
                    } else if (this.type === 'edit') {
                        if (this.form.status === '2' || this.form.status === '5') {
                            this.form.status = '0'
                        }
                        if (this.checked === false) {
                            this.form.ntSource = ''
                            this.form.ntLink = ''
                        }
                        getNewOptions(this.form).then((res) => {

                            loading.close();
                            if (res.data.code === 200) {
                                this.$message({
                                    message: res.data.message,
                                    type: "success",
                                });
                                this.$emit('getNewList')
                                this.dialogVisible = false

                            } else {
                                this.$message.error(res.data.message);
                            }
                        });
                    }

                } else {
                    return false;
                }
            });
        },
        // 获取详情
        getDetail(id) {
            getNewDetail(id).then(res => {
                if (res.data.code === 200) {
                    // this.form = res.data.result
                    var list = res.data.result.fileDtos
                    if (list.length !== 0) {
                        list.forEach(item => {
                            this.fileAll.push({
                                name: item.name,
                                filePath: item.filePath,
                            });
                        })
                        list.forEach(item => {
                            this.form.fileDtos.push({
                                name: item.name,
                                filePath: item.filePath,
                            });
                        })
                    }
                    this.loading = false
                }
            })
        },
        // 限制上传的类型
        beforeAvatarUpload(file) {
            const isLt10M = file.size / 1024 / 1024 < 10;
            if (!isLt10M) {
                this.$message.error("上传图片大小不能超过 10M!");
                return false;
            }
            var testmsg = file.name.substring(file.name.lastIndexOf(".") + 1);
            const extension = testmsg === "jpg" || testmsg === "JPG";
            const extension2 = testmsg === "png" || testmsg === "PNG";
            if (!extension && !extension2) {
                this.$message({
                    message: "上传图片只能是 jpg, png格式!",
                    type: "error",
                });
                return false;
            }
        },
        // 上传文件成功
        handleAvatarSuccess(response, file) {
            this.imgUrl = URL.createObjectURL(file.raw);
            this.form.ntThumb = response.message;
            this.$refs.headimgUpload1.clearValidate(); // 关闭校验
        },
        // 上传文件失败
        handleError(err) {
            let errInfo = JSON.parse(err["message"]);
            this.$message.error(`文件上传失败，原因:${errInfo.message}`);
        },
        //附件上传方法结束
        onEditorChange({ editor, html, text }) {
            this.form.content = html;
        },
        // 上传文件成功
        handleAvatarSuccess6(response, file) {
            let params = {
                name: file.name,
                filePath: file.response.message,
            }
            this.form.fileDtos.push(params);
        },
        // 上传文件失败
        handleError6(err) {
            let errInfo = JSON.parse(err["message"]);
            this.$message.error(`文件上传失败，原因：${errInfo.message}`);
        },
        //删除上传的文件
        handleRemove6(response, file, fileList) {
            var dataList = this.form.fileDtos;
            for (var i = 0; i < dataList.length; i++) {
                if (dataList[i].name.indexOf(response.name) > -1) {
                    var index = i;
                    dataList.splice(index, 1); //存在即删除
                }
            }
            this.form.fileDtos = dataList
        },

        // 富文本
        onCreated(editor) {
            this.editor = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
        },
        // 富文本-上传图片
        uploadImg(file, insertFn) {
            let imgData = new FormData();
            imgData.append('file', file);
            //调接口，上传图片
            getUploadImg(imgData).then(response => {
                if (response.data.code == 200) {
                    insertFn(response.data.message);
                } else {
                    this.$message.error(response.data.message);
                }
            })
        },
        // 富文本-上传视频
        uploadVideo(file, insertFn) {
            let imgData = new FormData();
            imgData.append('file', file);
            //调接口，上传图片
            getUploadImg(imgData).then(response => {
                if (response.data.code == 200) {
                    insertFn(response.data.message);
                } else {
                    this.$message.error(response.data.message);
                }
            })
        }
    },
    // 生命周期-离开当前页面路由
    beforeDestroy() {
        const editor = this.editor
        if (editor == null) return
        editor.destroy() // 组件销毁时，及时销毁编辑器
    }
};
</script>
<style src="@wangeditor/editor/dist/css/style.css"></style>
<style lang="less" scoped>
::v-deep .ql-editor {
    min-height: 200px;
}

.el-input {
    width: 420px;
}

.el-cascader {
    width: 420px;
}

.el-textarea {
    width: 420px;
}

/deep/.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 120px;
    height: 120px;
    line-height: 120px;
    text-align: center;
}

.avatar {
    width: 120px;
    height: 120px;
    display: block;
    object-fit: contain;
}

.newDesc {
    position: relative;

    .el-checkbox {
        position: absolute;
        top: 14.5%;
        left: 11%;
    }
}

.ql-toolbar {
    position: fixed;
}
</style>

